﻿/**
<code>
  <author name="Zealic" email="zealic(at)gmail.com" type="Creator"/>
</code>
**/
using System;

namespace Zealib.Numeric
{
    internal static class NumericHelper
    {
        public static uint[] Resize(uint[] v, int len)
        {
            if (v.Length == len) return v;
            uint[] result = new uint[len];
            int length = Math.Min(v.Length, len);
            Array.Copy(v, result, length);
            return result;
        }

        public static int GetLength(uint[] data)
        {
            if (data == null) return 0;
            int len = data.Length - 1;
            while ((len >= 0) && (data[len] == 0)) len--;
            return (len + 1);
        }

        public static void SetBit(int[] data, int bitIndex, bool value)
        {
            if (BitConverter.IsLittleEndian)
            {
                int byteIndex = 0;
                if (bitIndex > 7)
                {
                    byteIndex = Math.DivRem(bitIndex, 8, out bitIndex);
                }
                int xor = 1 << bitIndex;
                if (((data[byteIndex] & xor) == xor) != value)
                {
                    data[byteIndex] = data[byteIndex] ^ xor;
                }
            }
            else
            {
                throw new NotSupportedException();
            }
        }

        public static bool GetBit(uint[] data, int bitIndex)
        {
            if (BitConverter.IsLittleEndian)
            {
                int byteIndex = 0;
                if (bitIndex > 7)
                {
                    byteIndex = Math.DivRem(bitIndex, 8, out bitIndex);
                }
                int xor = 1 << bitIndex;
                return ((data[byteIndex] & xor) == xor);
            }
            else
            {
                throw new NotSupportedException();
            }
        }

    }
}

